package com.hzw.controller;

import com.hzw.dto.ApiResult;
import com.hzw.bean.User;
import com.hzw.dto.UserInfo;
import com.hzw.service.RegisterService;
import com.hzw.service.UserService;
import com.hzw.utils.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import static com.hzw.api.Api.CLIENT_ERROR;
import static com.hzw.api.Api.SERVER_ERROR;

/**
 * Created by Administrator on 2019/2/27.
 */

@Controller
@CrossOrigin
@RequestMapping(value = "/register")
public class RegisterController {
    @Resource
    private RegisterService registerService;

    @Resource
    private UserService userService;


    /**
     * 检查用户名是否已存在
     */
    @RequestMapping(value = "/checkExistUserName",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult checkExistUserName(@RequestBody User user){
        ApiResult result = new ApiResult(); //默认请求成功
        String userName = null;
        int count = 0;
        if(!ObjectUtils.isNullOrEmpty(user)){
            userName = user.getUserName();
        }else{
            return result.error(CLIENT_ERROR, "用户名不能为空");
        }

        try{
            count = userService.checkExistUserName(userName);
        }catch (Exception e){
            return result.error(SERVER_ERROR,e.getMessage());
        }

        if(count > 0){     //用户名已存在
            return result.error(CLIENT_ERROR, "用户名已存在");
        }else {
            result.setMsg("用户名可使用");
        }
        return result;
    }

    /**
     * 注册，保存用户名和密码(安全起见，密码由前端加密，后端直接保存)
     * 利用userId生成token返回给客户端浏览器
     */
    @RequestMapping(value = "/registerUser",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult registerUser(@RequestBody User user){
        ApiResult result = new ApiResult();
        UserInfo userInfo = null;
        try{
            userInfo = registerService.register(user);
        }catch (Exception e){
            return result.error(SERVER_ERROR, e.getMessage());
        }
        if(!ObjectUtils.isNullOrEmpty(userInfo)){
            result.setMsg("注册成功！");
            result.setData(userInfo);
        }else{
            return result.error(SERVER_ERROR,"返回用户信息失败");
        }
        return result;
    }

}
